/**
 * 
 */
package com.oet.service.manager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;



import com.oet.persistence.entity.UploadedFile;
import com.oet.service.data.Image;
import com.oet.utility.RandomString;
import com.oet.webservice.business.data.SimWebServiceFile;

/**
 * @author y140zhan
 *
 */
public class FileManager {
	
	private final static Logger logger = Logger.getLogger(FileManager.class.getName());
	public static final String FILE_KEY_COURSE_FILE="courseFile";
	public static final String FILE_KEY_COURSE_NEWS="courseNews";
	public static final String FILE_KEY_COURSE="course";
	public static final String FILE_KEY_CUSTOMER="customer";
	public static final String FILE_KEY_TEACHER="teacher";
	public static final String FILE_KEY_EVENT="event";
	public static final String FILE_KEY_BACKUP="backup";
//	public static final String FILE_KEY_CLIENTAPPLE="clientApple";
	
	public static final String FILE_GPB_SUBJECT_PIC_PATH_BASE="http://www.yueduke.com/YdkGpbChannelPic/";
	public static final String FILE_GPB_SUBJECT_PIC_PATH_BASE_BOOK="http://www.yueduke.com/YdkAdmin/gpbBookPic.do?name=";
	public static final String FILE_GPB_PICBOOK_PATH_BASE_BOOK="http://www.yueduke.com/picBook/";
	
//	public static final String FILE_KEY_INTERVIEW="interview";
//	public static final String FILE_KEY_INTERVIEW="interview";
//	public static final String FILE_KEY_INTERVIEW="interview";
//	public static final String FILE_KEY_INTERVIEW="interview";
//	public static final String FILE_KEY_INTERVIEW="interview";
//	public static final String FILE_KEY_INTERVIEW="interview";
	
	protected static String basePath;
	protected static Map<String, String>paths = null;
	protected static String splitor;

	
	
	
	
	/**
	 * @return the basePath
	 */
	public String getBasePath() {
		return basePath;
	}

	/**
	 * @param basePath the basePath to set
	 */
	public  void setBasePath(String basePath) {
		FileManager.basePath = basePath;
	}
	
	
	public static String getSplitor() {
		return splitor;
	}

	public static void setSplitor(String splitor) {
		FileManager.splitor = splitor;
	}

	public void setPaths(Map<String, String> paths)
	{
		this.paths = paths;
		if (basePath != null && paths != null)
		{
			Iterator it = paths.entrySet().iterator();
			File base = new File(basePath);
			if (!base.exists())
			{
				logger.error("About to create directory: " + base.getName());
				boolean success = base.mkdir();
				if (!success)
				{
					logger.error("Failed to create directory: " + base.getName());
				}
			}
			while(it.hasNext())
			{
				Map.Entry pairs = (Map.Entry)it.next();
				String name = pairs.getValue().toString();
//				name = name.substring(0, name.length() - 1);
				File test = new File(basePath + name);
				
				if (!test.exists())
				{
					logger.error("About to create directory: " + test.getName());
					boolean success = test.mkdir();
					if (!success)
					{
						logger.error("Failed to create directory: " + test.getName());
					}
				}
			}
			
		}
	}
	
	public static String getPath(String key)
	{
		if (paths != null)
		{
			return paths.get(key);
		}
		return null;
	}
	
	public static String getAbsolutePath(String key)
	{
		if (paths != null)
		{
			return basePath + paths.get(key);
		}
		return null;
	}
	
	public static String generateFileName(String key)
	{
		if (paths != null)
		{
			return paths.get(key) 
				+ new Long((new Date()).getTime()) + "_" 
				+ RandomString.getRandomString(4) +"_";
		}
		return null;
	}
	
	public static String generateFileName(String key, String ydkBookId)
	{
		if (paths != null)
		{
			if (ydkBookId != null && !ydkBookId.isEmpty())
			{
				String firstDirStr = paths.get(key) + ydkBookId.substring(0, 2);
				String secondDirStr = firstDirStr + "\\" + ydkBookId.substring(2, 4);
				File firstDir = new File(basePath + firstDirStr);
				File secondDir = new File(basePath + secondDirStr);
				if (!firstDir.exists())
				{
					firstDir.mkdirs();
				}
				
				if (!secondDir.exists())
				{
					secondDir.mkdirs();
				}
				
				return secondDirStr + "\\"
					+ new Long((new Date()).getTime()) + "_" 
					+ RandomString.getRandomString(4) +"_";
			}
			else
			{
				return paths.get(key) 
					+ new Long((new Date()).getTime()) + "_" 
					+ RandomString.getRandomString(4) +"_";
			}
		}
		return null;
	}
	
	public static String checkFileName(String fileName)
	{
		if (paths == null) 
		{
			logger.error("Could not get file path");
			return "Could not get file path";
		}
		if (paths != null)
		{
			
			File test = new File(basePath + fileName);
			if (!test.isFile())
			{
				logger.error("It is Not a file specified by: " + fileName);
				return "It is Not a file specified by : " + fileName;
			}
			if (!test.exists())
			{
				logger.error("Could not get file :" + fileName);
				return "Could not get file: " + fileName;
			}
		}
		return null;
	}
	
	public static void saveAsFile(String name, byte[] content)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath + name);
			try {
				FileCopyUtils.copy(content, tempFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("Save file " + name + "Error!");
				e.printStackTrace();
			}
			
		}
	}
	public static void saveAsFileUtf8(String name, byte[] content)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath + name);
			try {
				FileOutputStream out = new FileOutputStream(tempFile);
				BufferedOutputStream os = new BufferedOutputStream(out);
//				OutputStreamWriter  bos = new OutputStreamWriter(os,"utf-8");
				os.write(content);
				os.flush();
				os.close();
				out.close();
//				FileCopyUtils.copy(content, tempFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("Save file " + name + "Error!");
				e.printStackTrace();
			}
			
		}
	}
	
	public static void saveAsFileUtf8(String name, String content)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath + name);
			try {
				FileOutputStream out = new FileOutputStream(tempFile);
//				BufferedOutputStream os = new BufferedOutputStream(out);
				OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
				Writer writer = new BufferedWriter(osw); 
				writer.write(content);
//				OutputStreamWriter  bos = new OutputStreamWriter(os,"utf-8");
//				os.write(content);
				writer.flush();
				writer.close();
//				os.flush();
//				os.close();
//				out.close();
//				FileCopyUtils.copy(content, tempFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("Save file " + name + "Error!");
				e.printStackTrace();
			}
			
		}
	}
	
	public static byte[] loadFile(String name)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath +name);
			try {
				return FileCopyUtils.copyToByteArray(tempFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("Load file " + name + "Error!");
				e.printStackTrace();
			}
			
		}
		return null;
	}
	
	public static void deleteFileByName(String name)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath +name);
			if (tempFile.exists())
			{
				try {
					tempFile.delete();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("Delete file " + name + "Error!");
					e.printStackTrace();
				}
			}
			
		}
		return;
	}

	public static void renameFileByName(String oldName, String newName)
	{
		if (oldName == null || newName == null)
		{
			return;
		}

		File oldFile = new File(basePath + oldName);
		File newFile = new File(basePath + newName);
		if (oldFile.exists())
		{
			try {
				oldFile.renameTo(newFile);
			} catch (Exception e) {
				logger.error("Rename file " + oldName + " to " + newName + " Error!");
				e.printStackTrace();
			}
		}
	}
	
	public static File getFileByName(String fileName)
	{
		if (fileName != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath +fileName);
			if (!tempFile.isFile())
			{
				logger.error("It is Not a file specified by: " + fileName);
				return null;
			}
			if (!tempFile.exists())
			{
				logger.error("Could not get file :" + fileName);
				return null;
			}
			return tempFile;
			
		}
		return null;
	}
	
	public static File createFileByName(String fileName)
	{
		if (fileName != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath +fileName);
//			if (!tempFile.isFile())
//			{
//				logger.error("It is Not a file specified by: " + fileName);
//				return null;
//			}
			return tempFile;
			
		}
		return null;
	}
	
	public static UploadedFile loadUploadedFile(String name)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath +name);
			UploadedFile result = new UploadedFile();
			result.setFileName(tempFile.getName());
			result.setFileSize(tempFile.length());
			
			try {
				result.setFileContent(FileCopyUtils.copyToByteArray(tempFile));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("Load file " + name + "Error!");
				e.printStackTrace();
			}
//			result.setFileType(tempFile.)
			return result;
		}
		return null;
	}
	
	public static SimWebServiceFile loadSimWebServiceFileFile(String name)
	{
		if (name != null)
		{
			//ToDo move this to background task;
			File tempFile = new File(basePath +name);
			SimWebServiceFile result = new SimWebServiceFile();
			result.setFileName(tempFile.getName());
			result.setFileSize(tempFile.length());
			
			try {
				result.setContent(FileCopyUtils.copyToByteArray(tempFile));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("Load file " + name + "Error!");
				e.printStackTrace();
			}
//			result.setFileType(tempFile.)
			return result;
		}
		return null;
	}
	
	/*
	
	public static EpubBook parseEpubZip(String fileName) throws Exception
	{
		//ToDo move this to background task;
		EpubBook epubBook = new EpubBook(basePath +fileName);

		epubBook.parseMetadata();

		return epubBook;
	}
	
	
	public static Book parseEpubBook(String fileName) throws Exception
	{
		if (fileName != null)
		{
			EpubBook epubBook = new EpubBook(basePath +fileName);
			epubBook.parseMetadata();
			
			Book book = new Book();
			book.setBookContent(fileName);
			if (epubBook.getAuthors() != null)
			{
				if (epubBook.getAuthors().size() > 4)
				{
					for (int i =4; i < epubBook.getAuthors().size(); i ++)
					{
						if (epubBook.getAuthors().get(i) != null && 
								!epubBook.getAuthors().get(i).isEmpty())
						book.getAuthorOthers().add(epubBook.getAuthors().get(i));
					}
				}
				if (epubBook.getAuthors().size() > 3)
				{
					if (epubBook.getAuthors().get(3) != null && 
							!epubBook.getAuthors().get(3).isEmpty())
					book.setAuthor3(new Author(epubBook.getAuthors().get(3)));
				}
				if (epubBook.getAuthors().size() > 2)
				{
					if (epubBook.getAuthors().get(2) != null && 
							!epubBook.getAuthors().get(2).isEmpty())
					book.setAuthor2(new Author(epubBook.getAuthors().get(2)));
				}
				if (epubBook.getAuthors().size() > 1)
				{
					if (epubBook.getAuthors().get(1) != null && 
							!epubBook.getAuthors().get(1).isEmpty())
					book.setAuthor1(new Author(epubBook.getAuthors().get(1)));
				}
				if (epubBook.getAuthors().size() > 0)
				{	
					if (epubBook.getAuthors().get(0) != null && 
							!epubBook.getAuthors().get(0).isEmpty())
					book.setAuthor(new Author(epubBook.getAuthors().get(0)));
				}
				
			}
			
			if (epubBook.getTranslators() != null)
			{
				
				if (epubBook.getTranslators().size() > 4)
				{
					for (int i =4; i < epubBook.getTranslators().size(); i ++)
					{
						if (epubBook.getTranslators().get(i) != null && 
								!epubBook.getTranslators().get(i).isEmpty())
						book.getTranslatorOthers().add(epubBook.getTranslators().get(i));
					}
				}
				if (epubBook.getTranslators().size() > 3)
				{
					if (epubBook.getTranslators().get(3) != null && 
							!epubBook.getTranslators().get(3).isEmpty())
					book.setTranslator3(new Translator(epubBook.getTranslators().get(3)));
				}
				if (epubBook.getTranslators().size() > 2)
				{
					if (epubBook.getTranslators().get(2) != null && 
							!epubBook.getTranslators().get(2).isEmpty())
					book.setTranslator2(new Translator(epubBook.getTranslators().get(2)));
				}
				if (epubBook.getTranslators().size() > 1)
				{
					if (epubBook.getTranslators().get(1) != null && 
							!epubBook.getTranslators().get(1).isEmpty())
					book.setTranslator1(new Translator(epubBook.getTranslators().get(1)));
				}
				if (epubBook.getTranslators().size() > 0)
				{	
					if (epubBook.getTranslators().get(0) != null && 
							!epubBook.getTranslators().get(0).isEmpty())
					book.setTranslator(new Translator(epubBook.getTranslators().get(0)));
				}
			}
			
			book.setTitle(epubBook.getTitle());
			book.setYdkBookId(epubBook.getBookUUID());
			//epubBook.getFormat();
			book.setSummary(epubBook.getIntroduction());
			
			//ISBN is Integer.
			book.setIsbn((epubBook.getIsbn()));
//			epubBook.getLayout();
			try {
				book.setPages(new Integer(epubBook.getPages()));
			}catch (Exception e){
				logger.debug("getPages exception:"+e);
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss-SSS aa");
			dateFormat.setLenient(true);
			try
			{
				book.setPublishDate(dateFormat.parse(epubBook.getPublishDate()));
			}
			catch(Exception e)
			{
				book.setPublishDate(new Date());
			}
			if(epubBook.getPublisher() != null && !epubBook.getPublisher().isEmpty())
			{
				book.setPublisher(new Publisher(epubBook.getPublisher()));
			}
			book.setPaperPrice(Double.parseDouble(epubBook.getPaperCopyPrice()));
			
			//Images
			Image img = epubBook.getThumbnailSmall();
			if (img != null)
			{
				saveAsFile(fileName + "is", img.data);
				book.setImageSmall(fileName + "is");
			}
			
			img = epubBook.getThumbnailBig();
			if (img != null)
			{
				saveAsFile(fileName + "ib", img.data);
				book.setImageLarge(fileName + "ib");
			}
			
			img = epubBook.getThumbnail3DSmall();
			if (img != null)
			{
				saveAsFile(fileName + "3ds", img.data);
				book.setImage3DSmall(fileName + "3ds");
			}
			
			img = epubBook.getThumbnail3DBig();
			if (img != null)
			{
				saveAsFile(fileName + "3db", img.data);
				book.setImage3DLarge(fileName + "3db");
			}
			
//			result.setFileType(tempFile.)
			return book;
		}
		return null;
	}
	
	
	public static EpubBook readEpubBook(String fileName) throws Exception
	{
		if (fileName != null)
		{
			EpubBook epubBook = new EpubBook(basePath +fileName);
			epubBook.parseMetadata();
			
			return epubBook;
		}
		return null;
	}
	
	public static Book parseEpubBook(String fileName, EpubBook epubBook) throws Exception
	{
		if (epubBook != null && fileName != null)
		{
			
			Book book = new Book();
			book.setBookContent(fileName);
			if (epubBook.getAuthors() != null)
			{
				if (epubBook.getAuthors().size() > 4)
				{
					for (int i =4; i < epubBook.getAuthors().size(); i ++)
					{
						if (epubBook.getAuthors().get(i) != null && 
								!epubBook.getAuthors().get(i).isEmpty())
						book.getAuthorOthers().add(epubBook.getAuthors().get(i));
					}
				}
				if (epubBook.getAuthors().size() > 3)
				{
					if (epubBook.getAuthors().get(3) != null && 
							!epubBook.getAuthors().get(3).isEmpty())
					book.setAuthor3(new Author(epubBook.getAuthors().get(3)));
				}
				if (epubBook.getAuthors().size() > 2)
				{
					if (epubBook.getAuthors().get(2) != null && 
							!epubBook.getAuthors().get(2).isEmpty())
					book.setAuthor2(new Author(epubBook.getAuthors().get(2)));
				}
				if (epubBook.getAuthors().size() > 1)
				{
					if (epubBook.getAuthors().get(1) != null && 
							!epubBook.getAuthors().get(1).isEmpty())
					book.setAuthor1(new Author(epubBook.getAuthors().get(1)));
				}
				if (epubBook.getAuthors().size() > 0)
				{	
					if (epubBook.getAuthors().get(0) != null && 
							!epubBook.getAuthors().get(0).isEmpty())
					book.setAuthor(new Author(epubBook.getAuthors().get(0)));
				}
				
			}
			
			if (epubBook.getTranslators() != null)
			{
				
				if (epubBook.getTranslators().size() > 4)
				{
					for (int i =4; i < epubBook.getTranslators().size(); i ++)
					{
						if (epubBook.getTranslators().get(i) != null && 
								!epubBook.getTranslators().get(i).isEmpty())
						book.getTranslatorOthers().add(epubBook.getTranslators().get(i));
					}
				}
				if (epubBook.getTranslators().size() > 3)
				{
					if (epubBook.getTranslators().get(3) != null && 
							!epubBook.getTranslators().get(3).isEmpty())
					book.setTranslator3(new Translator(epubBook.getTranslators().get(3)));
				}
				if (epubBook.getTranslators().size() > 2)
				{
					if (epubBook.getTranslators().get(2) != null && 
							!epubBook.getTranslators().get(2).isEmpty())
					book.setTranslator2(new Translator(epubBook.getTranslators().get(2)));
				}
				if (epubBook.getTranslators().size() > 1)
				{
					if (epubBook.getTranslators().get(1) != null && 
							!epubBook.getTranslators().get(1).isEmpty())
					book.setTranslator1(new Translator(epubBook.getTranslators().get(1)));
				}
				if (epubBook.getTranslators().size() > 0)
				{	
					if (epubBook.getTranslators().get(0) != null && 
							!epubBook.getTranslators().get(0).isEmpty())
					book.setTranslator(new Translator(epubBook.getTranslators().get(0)));
				}
			}
			
			book.setTitle(epubBook.getTitle());
			book.setYdkBookId(epubBook.getBookUUID());
			//epubBook.getFormat();
			book.setSummary(epubBook.getIntroduction());
			
			//ISBN is Integer.
			book.setIsbn((epubBook.getIsbn()));
//			epubBook.getLayout();
			try {
				book.setPages(new Integer(epubBook.getPages()));
			}catch (Exception e){
				logger.debug("getPages exception:"+e);
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss-SSS aa");
			dateFormat.setLenient(true);
			try
			{
				book.setPublishDate(dateFormat.parse(epubBook.getPublishDate()));
			}
			catch(Exception e)
			{
				book.setPublishDate(new Date());
			}
			if(epubBook.getPublisher() != null && !epubBook.getPublisher().isEmpty())
			{
				book.setPublisher(new Publisher(epubBook.getPublisher()));
			}
			try {
				book.setPaperPrice(Double.parseDouble(epubBook.getPaperCopyPrice()));
			}catch (Exception e){
				logger.debug("getPapterCopyPrice exception:"+e);
			}
			
			//Images
			Image img = epubBook.getThumbnailSmall();
			if (img != null)
			{
				saveAsFile(fileName + "is", img.data);
				book.setImageSmall(fileName + "is");
			}
			
			img = epubBook.getThumbnailBig();
			if (img != null)
			{
				saveAsFile(fileName + "ib", img.data);
				book.setImageLarge(fileName + "ib");
			}
			
			img = epubBook.getThumbnail3DSmall();
			if (img != null)
			{
				saveAsFile(fileName + "3ds", img.data);
				book.setImage3DSmall(fileName + "3ds");
			}
			
			img = epubBook.getThumbnail3DBig();
			if (img != null)
			{
				saveAsFile(fileName + "3db", img.data);
				book.setImage3DLarge(fileName + "3db");
			}
			
//			result.setFileType(tempFile.)
			return book;
		}
		return null;
	}
	
	public static Book updateByEpubBook(Book book, String fileName, EpubBook epubBook) throws Exception
	{
		if (epubBook != null && fileName != null)
		{
			
//			Book book = new Book();
			book.setBookContent(fileName);
			if (epubBook.getAuthors() != null)
			{
				if (epubBook.getAuthors().size() > 4)
				{
					book.getAuthorOthers().clear();
					for (int i =4; i < epubBook.getAuthors().size(); i ++)
					{
						if (epubBook.getAuthors().get(i) != null && 
								!epubBook.getAuthors().get(i).isEmpty())
						book.getAuthorOthers().add(epubBook.getAuthors().get(i));
					}
				}
				if (epubBook.getAuthors().size() > 3)
				{
					if (epubBook.getAuthors().get(3) != null && 
							!epubBook.getAuthors().get(3).isEmpty())
					book.setAuthor3(new Author(epubBook.getAuthors().get(3)));
				}
				if (epubBook.getAuthors().size() > 2)
				{
					if (epubBook.getAuthors().get(2) != null && 
							!epubBook.getAuthors().get(2).isEmpty())
					book.setAuthor2(new Author(epubBook.getAuthors().get(2)));
				}
				if (epubBook.getAuthors().size() > 1)
				{
					if (epubBook.getAuthors().get(1) != null && 
							!epubBook.getAuthors().get(1).isEmpty())
					book.setAuthor1(new Author(epubBook.getAuthors().get(1)));
				}
				if (epubBook.getAuthors().size() > 0)
				{	
					if (epubBook.getAuthors().get(0) != null && 
							!epubBook.getAuthors().get(0).isEmpty())
					book.setAuthor(new Author(epubBook.getAuthors().get(0)));
				}
				
			}
			
			if (epubBook.getTranslators() != null)
			{
				
				if (epubBook.getTranslators().size() > 4)
				{
					book.getTranslatorOthers().clear();
					for (int i =4; i < epubBook.getTranslators().size(); i ++)
					{
						if (epubBook.getTranslators().get(i) != null && 
								!epubBook.getTranslators().get(i).isEmpty())
						book.getTranslatorOthers().add(epubBook.getTranslators().get(i));
					}
				}
				if (epubBook.getTranslators().size() > 3)
				{
					if (epubBook.getTranslators().get(3) != null && 
							!epubBook.getTranslators().get(3).isEmpty())
					book.setTranslator3(new Translator(epubBook.getTranslators().get(3)));
				}
				if (epubBook.getTranslators().size() > 2)
				{
					if (epubBook.getTranslators().get(2) != null && 
							!epubBook.getTranslators().get(2).isEmpty())
					book.setTranslator2(new Translator(epubBook.getTranslators().get(2)));
				}
				if (epubBook.getTranslators().size() > 1)
				{
					if (epubBook.getTranslators().get(1) != null && 
							!epubBook.getTranslators().get(1).isEmpty())
					book.setTranslator1(new Translator(epubBook.getTranslators().get(1)));
				}
				if (epubBook.getTranslators().size() > 0)
				{	
					if (epubBook.getTranslators().get(0) != null && 
							!epubBook.getTranslators().get(0).isEmpty())
					book.setTranslator(new Translator(epubBook.getTranslators().get(0)));
				}
			}
			
			book.setTitle(epubBook.getTitle());
			book.setYdkBookId(epubBook.getBookUUID());
			//epubBook.getFormat();
			book.setSummary(epubBook.getIntroduction());
			
			//ISBN is Integer.
			book.setIsbn((epubBook.getIsbn()));
//			epubBook.getLayout();
			if (epubBook.getPages() != null || !epubBook.getPages().isEmpty())
			{
				try {
					book.setPages(new Integer(epubBook.getPages()));
				}catch (Exception e){
					book.setPages(0);
				}
			}
			else
			{
				book.setPages(0);
			}
			
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss-SSS aa");
			dateFormat.setLenient(true);
			try
			{
				book.setPublishDate(dateFormat.parse(epubBook.getPublishDate()));
			}
			catch(Exception e)
			{
				book.setPublishDate(new Date());
			}
			if(epubBook.getPublisher() != null && !epubBook.getPublisher().isEmpty())
			{
				book.setPublisher(new Publisher(epubBook.getPublisher()));
			}
			try {
				book.setPaperPrice(Double.parseDouble(epubBook.getPaperCopyPrice()));
			}catch (Exception e){
				
			}
			
			//Images
			Image img = epubBook.getThumbnailSmall();
			if (img != null)
			{
				saveAsFile(fileName + "is", img.data);
				book.setImageSmall(fileName + "is");
			}
			
			img = epubBook.getThumbnailBig();
			if (img != null)
			{
				saveAsFile(fileName + "ib", img.data);
				book.setImageLarge(fileName + "ib");
			}
			
			img = epubBook.getThumbnail3DSmall();
			if (img != null)
			{
				saveAsFile(fileName + "3ds", img.data);
				book.setImage3DSmall(fileName + "3ds");
			}
			
			img = epubBook.getThumbnail3DBig();
			if (img != null)
			{
				saveAsFile(fileName + "3db", img.data);
				book.setImage3DLarge(fileName + "3db");
			}
			
//			result.setFileType(tempFile.)
			return book;
		}
		return null;
	}
	
	public static void createTxtFromEpub(EpubBook epubbook, Book book, Key key,
			BookDbMngr bookDbMngr)
	{
		BookContent bookContent = null;
		List<String> tocList = new ArrayList<String>(0);
		try {
			if(epubbook != null)
				tocList = epubbook.getTocTitleList(key.getPublicKey());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Here we need to store the file/images to specific path
		//and add the fileDescriptor to instance.
		String fileName = FileManager.generateFileName(FileManager.FILE_KEY_BOOK_TXT);
		if (fileName == null)
		{
			logger.error("Could not generate File name");
			return ;
		}
		
		
		bookContent = new BookContent();
		bookContent.setBookId(book.getId());
		bookContent.setYdkBookId(book.getYdkBookId());
		bookContent.setBookSize(book.getSize());
		bookContent.setTitle(book.getTitle());
		bookContent.setTotalChapter(tocList.size());
		bookContent.setChapterTitles((ArrayList<String>) tocList);
		bookContent.setImage3DLarge(book.getImage3DLarge());
		bookContent.setImage3DSmall(book.getImage3DSmall());
		bookContent.setImageLarge(book.getImageLarge());
		bookContent.setImageSmall(book.getImageSmall());
		
		String bookContextTxt = "";
//		try {
//			if(epubbook != null)
//				bookContextTxt = epubbook.getFullContentTextTxt(key.getPublicKey());
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
		
		
		for (int i = 0; i < tocList.size(); i++)
		{
			String chapterContent = null;
			try {
				if(epubbook != null)
					chapterContent = epubbook.getChapterContextTxt(key.getPublicKey(), i+1);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			for (;chapterContent.startsWith("\r\n");)
			{
				chapterContent = chapterContent.substring(2);
			}
			
			for (;chapterContent.endsWith("\r\n");)
			{
				chapterContent = chapterContent.substring(0, chapterContent.length() -2 );
			}
			
			//Now we also need to do the text -> html transformation

			chapterContent = chapterContent.replace("\r\n\r\n\r\n", "\r\n");
//			chapterContent = chapterContent.replace("\r\n\r\n", "\r\n" );
//			chapterContent = chapterContent.replace("\n\n\n\n\n", "<br/>");
//			chapterContent = chapterContent.replace("\n\n\n\n", "<br/>");
//			chapterContent = chapterContent.replace("\n", "<br/>");
//			chapterContent = chapterContent.replace(" ", "&nbsp;");
			
//			chapterContent = chapterContent.replace("\n", "\r\n");
			int index = chapterContent.indexOf(tocList.get(i).trim());
			if (index == -1)
			{
//				chapterContent = tocList.get(i) + "\r\n" + chapterContent;
			}
			else
			{
				int index2 = chapterContent.indexOf(tocList.get(i).trim(), index + 2);
				if (index2 != -1)
				{
					chapterContent = chapterContent.substring(index2);
				}
			}
			
			FileManager.saveAsFileUtf8(fileName + "ch" + (i), chapterContent);
			bookContent.getChapterTxts().add(fileName + "ch" + i);
			
			bookContextTxt += (chapterContent + "\r\n\r\n");
			
		}
		

		FileManager.saveAsFileUtf8(fileName + "bc", bookContextTxt);
		bookContent.setBookWholeTxt(fileName + "bc");
		
		bookDbMngr.storeBookContent(bookContent);
	}
	
	
	public static void updateTxtFromEpub(EpubBook epubbook, Book book, Key key,
			BookDbMngr bookDbMngr)
	{
		BookContent bookContent = bookDbMngr.getBookContent(book.getYdkBookId());
		if (bookContent != null)
		{
		List<String> tocList = new ArrayList<String>(0);
		try {
			if(epubbook != null)
				tocList = epubbook.getTocTitleList(key.getPublicKey());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Here we need to store the file/images to specific path
		//and add the fileDescriptor to instance.
		String fileName = FileManager.generateFileName(FileManager.FILE_KEY_BOOK_TXT);
		if (fileName == null)
		{
			logger.error("Could not generate File name");
			return ;
		}
		
		
//		bookContent = new BookContent();
		bookContent.setBookId(book.getId());
		bookContent.setYdkBookId(book.getYdkBookId());
		bookContent.setBookSize(book.getSize());
		bookContent.setTitle(book.getTitle());
		bookContent.setTotalChapter(tocList.size());
		bookContent.setChapterTitles((ArrayList<String>) tocList);
		bookContent.setImage3DLarge(book.getImage3DLarge());
		bookContent.setImage3DSmall(book.getImage3DSmall());
		bookContent.setImageLarge(book.getImageLarge());
		bookContent.setImageSmall(book.getImageSmall());
		
		String oldBookContextTxt = bookContent.getBookWholeTxt();
		List<String> oldChapterTxts = bookContent.getChapterTxts();
		bookContent.setChapterTxts(new ArrayList<String>(0));
		
		String bookContextTxt = "";
//		try {
//			if(epubbook != null)
//				bookContextTxt = epubbook.getFullContentTextTxt(key.getPublicKey());
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
		
		
		for (int i = 0; i < tocList.size(); i++)
		{
			String chapterContent = null;
			try {
				if(epubbook != null)
					chapterContent = epubbook.getChapterContextTxt(key.getPublicKey(), i+1);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			for (;chapterContent.startsWith("\r\n");)
			{
				chapterContent = chapterContent.substring(2);
			}
			
			for (;chapterContent.endsWith("\r\n");)
			{
				chapterContent = chapterContent.substring(0, chapterContent.length() -2 );
			}
			
			//Now we also need to do the text -> html transformation

			chapterContent = chapterContent.replace("\r\n\r\n\r\n", "\r\n");
//			chapterContent = chapterContent.replace("\r\n\r\n", "\r\n" );
//			chapterContent = chapterContent.replace("\n\n\n\n\n", "<br/>");
//			chapterContent = chapterContent.replace("\n\n\n\n", "<br/>");
//			chapterContent = chapterContent.replace("\n", "<br/>");
//			chapterContent = chapterContent.replace(" ", "&nbsp;");
			
//			chapterContent = chapterContent.replace("\n", "\r\n");
			int index = chapterContent.indexOf(tocList.get(i).trim());
			if (index == -1)
			{
//				chapterContent = tocList.get(i) + "\r\n" + chapterContent;
			}
			else
			{
				int index2 = chapterContent.indexOf(tocList.get(i).trim(), index + 2);
				if (index2 != -1)
				{
					chapterContent = chapterContent.substring(index2);
				}
			}
			
			FileManager.saveAsFileUtf8(fileName + "ch" + (i), chapterContent);
			bookContent.getChapterTxts().add(fileName + "ch" + i);
			
			bookContextTxt += (chapterContent + "\r\n\r\n");
			
		}
		

		FileManager.saveAsFileUtf8(fileName + "bc", bookContextTxt);
		bookContent.setBookWholeTxt(fileName + "bc");
		
		bookDbMngr.updateBookContent(bookContent);
		
		
		//OK, now we need to do the clean up;
		if (oldBookContextTxt != null && !oldBookContextTxt.isEmpty())
		{
			FileManager.deleteFileByName(oldBookContextTxt);
		}
		if (oldChapterTxts != null)
		{
			for (String txt : oldChapterTxts)
			{
				if (txt != null && !txt.isEmpty())
				{
					FileManager.deleteFileByName(txt);
				}
			}
		}
		}
		
	}
	
	public static void deleTxtFromEpub(String ydkBookId, BookDbMngr bookDbMngr)
	{
		BookContent bookContent = bookDbMngr.getBookContent(ydkBookId);
		if (bookContent != null)
		{
			if (bookContent.getBookWholeTxt() != null && !bookContent.getBookWholeTxt().isEmpty())
			{
				FileManager.deleteFileByName(bookContent.getBookWholeTxt());
			}
			if (bookContent.getChapterTxts() != null)
			{
				for (String txt : bookContent.getChapterTxts())
				{
					if (txt != null && !txt.isEmpty())
					{
						FileManager.deleteFileByName(txt);
					}
				}
			}
			
			bookDbMngr.deleteBookContent(ydkBookId);
		}
		
	}

	public static void updateBookFiles(String srcDirStr, String destDirStr, BookDbMngr bookDbMngr)
	{
		long begintime = System.currentTimeMillis();		
		
		File destDir = new File(destDirStr);
		if (!destDir.exists())
		{
			System.out.println("目的文件夹\"" + destDirStr + "\"不存在.");
			return;
		}
		
		File oldDir = new File(srcDirStr);
		if (!oldDir.exists())
		{
			System.out.println("源文件夹\"" + srcDirStr + "\"不存在.");
			return;
		}
		
		File destBookDir = new File(destDirStr + "/book");
		if (!destBookDir.exists())
		{
			destBookDir.mkdirs();
		}
		
		List<Book> list = (List<Book>)bookDbMngr.getBooks();
		System.out.println("Total " + list.size() + " books.");
		
		for (Book book : list)
		{
			//if (book.getId() == 2312) {
			String ydkBookId = book.getYdkBookId();
			
			String firstDirStr = destDirStr + "/book/" + ydkBookId.substring(0, 2);
			String secondDirStr = firstDirStr + "/" + ydkBookId.substring(2, 4);
			String secondDirInDb = "book\\" + ydkBookId.substring(0, 2) + "\\" + ydkBookId.substring(2, 4);
			
			File firstDir = new File(firstDirStr);
			if (!firstDir.exists())
			{
				firstDir.mkdirs();
			}
			
			File secondDir = new File(secondDirStr);
			if (!secondDir.exists())
			{
				secondDir.mkdir();
			}
			
			// Copy book content
			if (book.getBookContent() != null)
			{
				String bookFn = book.getBookContent().substring(book.getBookContent().lastIndexOf("\\") + 1, 
																book.getBookContent().length());
				
				File srcFile = new File(srcDirStr + "/" + book.getBookContent());
				File dstFile = new File(secondDirStr + "/" + bookFn);
				
				if (srcFile.exists())
				{
					try {
						FileCopyUtils.copy(srcFile, dstFile);
					} catch (Exception e) {
						System.out.println("Failed copy file from " + srcDirStr + "/" + bookFn + " to " + secondDirStr + "/" + bookFn);
					}
					
					book.setBookContent(secondDirInDb + "\\" + bookFn);
				}
				else
				{
					System.out.println(srcFile.getAbsolutePath() + " does not exist." + " Book ID: " + book.getId());
				}
			}
			
			// Copy small image
			if (book.getImageSmall() != null)
			{
				String imageSfnStr = book.getImageSmall().substring(book.getImageSmall().lastIndexOf("\\") + 1, 
																	book.getImageSmall().length());
				
				File srcFile = new File(srcDirStr + "/" + book.getImageSmall());
				File dstFile = new File(secondDirStr + "/" + imageSfnStr);
				
				if (srcFile.exists())
				{
					try {
						FileCopyUtils.copy(srcFile, dstFile);
					} catch (Exception e) {
						System.out.println("Failed copy file from " + srcDirStr + "/" + imageSfnStr + " to " + secondDirStr + "/" + imageSfnStr);
					}
					
					book.setImageSmall(secondDirInDb + "\\" + imageSfnStr);
				}
				else
				{
					System.out.println(srcFile.getAbsolutePath() + " does not exist." + " Book ID: " + book.getId());
				}
			}
			
			// Copy large image
			if (book.getImageLarge() != null)
			{
				String imageLfnStr = book.getImageLarge().substring(book.getImageLarge().lastIndexOf("\\") + 1,
																	book.getImageLarge().length());
				
				File srcFile = new File(srcDirStr + "/" + book.getImageLarge());
				File dstFile = new File(secondDirStr + "/" + imageLfnStr);
				
				if (srcFile.exists())
				{
					try {
						FileCopyUtils.copy(srcFile, dstFile);
					} catch (Exception e) {
						System.out.println("Failed copy file from " + srcDirStr + "/" + imageLfnStr + " to " + secondDirStr + "/" + imageLfnStr);
					}
					
					book.setImageLarge(secondDirInDb + "\\" + imageLfnStr);
				}
				else
				{
					System.out.println(srcFile.getAbsolutePath() + " does not exist." + " Book ID: " + book.getId());
				}
			}
			
			// Copy 3D small image
			if (book.getImage3DSmall() != null)
			{
				String image3DsFnStr = book.getImage3DSmall().substring(book.getImage3DSmall().lastIndexOf("\\") + 1,
																		book.getImage3DSmall().length());
				
				File srcFile = new File(srcDirStr + "/" + book.getImage3DSmall());
				File dstFile = new File(secondDirStr + "/" + image3DsFnStr);
				
				if (srcFile.exists())
				{
					try {
						FileCopyUtils.copy(srcFile, dstFile);
					} catch (Exception e) {
						System.out.println("Failed copy file from " + srcDirStr + "/" + image3DsFnStr + " to " + secondDirStr + "/" + image3DsFnStr);
					}
					
					book.setImage3DSmall(secondDirInDb + "\\" + image3DsFnStr);
				}
				else
				{
					System.out.println(srcFile.getAbsolutePath() + " does not exist." + " Book ID: " + book.getId());
				}
			}
			
			// Copy 3D large image
			if (book.getImage3DLarge() != null)
			{
				String image3DlFnStr = book.getImage3DSmall().substring(book.getImage3DLarge().lastIndexOf("\\") + 1,
																		book.getImage3DLarge().length());
				
				File srcFile = new File(srcDirStr + "/" + book.getImage3DLarge());
				File dstFile = new File(secondDirStr + "/" + image3DlFnStr);
				
				if (srcFile.exists())
				{
					try {
						FileCopyUtils.copy(srcFile, dstFile);
					} catch (Exception e) {
						System.out.println("Failed copy file from " + srcDirStr + "/" + image3DlFnStr + " to " + secondDirStr + "/" + image3DlFnStr);
					}
					
					book.setImage3DLarge(secondDirInDb + "\\" + image3DlFnStr);
				}
				else
				{
					System.out.println(srcFile.getAbsolutePath() + " does not exist." + " Book ID: " + book.getId());
				}
			}
			
			try {
				bookDbMngr.saveBook(book);
			} catch (Exception e) {e.printStackTrace();}

		}
		
		long endtime = System.currentTimeMillis();
		System.out.println("Success copy files in " + (endtime - begintime)/1000 + "S.");
	}
	
*/
	public static Properties loadPropertyFromFile(String fileName)
	{
		if (fileName == null || fileName.isEmpty())
		{
			logger.error("Error load properties from file null: " + fileName);
			return null;
		}
		File file = new File(fileName);
		if (!file.exists() || !file.isFile())
		{
			logger.error("Error load properties from non-exist file: " + fileName);
			return null;
		}
		
		try
		{
			InputStream in = new BufferedInputStream(new FileInputStream(file));
			Properties prop = new Properties();
			prop.load(in);
			in.close();
			return prop;
		}catch (Exception e) {  
            e.printStackTrace();  
            logger.error("Error load properties from file: " + fileName);
            return null;  
        }  
	}
	
	
	public static Boolean savePropertyToFile(String fileName, Properties prop)
	{
		if (fileName == null || fileName.isEmpty())
		{
			logger.error("Error save properties to file null: " + fileName);
			return false;
		}
		File file = new File(fileName);
		if (!file.exists())
		{
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("Can not create file, Error save properties to file: " + fileName);
				return false;
			}
		}
		
		if (!file.canWrite())
		{
			logger.error("Error save properties to non-writable file: " + fileName);
			return false;
		}
		
		try
		{
			OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
			prop.store(out, new Date().toString());
			out.flush();
			out.close();
			return true;
		}catch (Exception e) {  
            e.printStackTrace();  
            logger.error("Error save properties to file: " + fileName);
            return false;  
        }  
	}
	

}
